package praktikumid.w06.p3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author Ago
 *
 */
public class PanoExample {
	
	// inline class, could be in a separate GoogleCoordinates.java file
	class GoogleCoordinates {
		public double latitudeMin;
		// etc.
		
		@Override
		public String toString() {
			// TODO Auto-generated method stub
			return "latmin:" + latitudeMin;
		}
	}

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		PanoExample p = new PanoExample("Tallinn");
		p.run();
		
		ArrayList<Car> list = new ArrayList<Car>();
	}
	
	private String location;
	public PanoExample(String location) {
		this.location = location;
	}
	
	public void run() throws IOException {
		
		String response1 = readWebPage("http://maps.googleapis.com/maps/api/geocode/xml?address=" + location + "&sensor=false");
		//String response1 = "   <southwest><lat>59.3518090</lat><lng>24.5501939</lng></southwest>"
		//			+ "<northeast><lat>59.5914239</lat><lng>24.9262889</lng></northeast>";
		// System.out.println(response1);
		GoogleCoordinates gc = parseGoogleResponse(response1);
		System.out.println(gc);
	}
	
	/**
	 * Reads a link and returns the response from the link as one-line String.
	 * @param link
	 * @return
	 * @throws IOException
	 */
	private String readWebPage(String link) throws IOException {
		String response = "";
		URL urlObject = new URL(link);
		BufferedReader br = new BufferedReader(new InputStreamReader(urlObject.openStream()));
		String line;
		while ((line = br.readLine()) != null) {
			response += line;
		}
		return response;
	}
	
	private GoogleCoordinates parseGoogleResponse(String response) {
		// start position of <bounds> element
		int startPos = response.indexOf("<bounds>");
		startPos = response.indexOf("<lat>", startPos);
		int endPos = response.indexOf("</lat>", startPos);
		// we have the start position of the first <lat>
		// and the start position of the first </lat>
		// everything between those is latitude
		String substr = response.substring(startPos + 5, endPos);
		// +5 because <lat> length
		// without +5 we would get <lat>1.234
		double d = Double.parseDouble(substr);
		GoogleCoordinates gc = new GoogleCoordinates();
		gc.latitudeMin = d;
		
		// TODO: handle exceptions like
		// location not found
		// parsing double failed etc.
		return gc;
	}

}
